package org.torproject.android;

import java.util.StringTokenizer;

import com.google.android.maps.GeoPoint;

import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;

public class RouterDescriptor implements Parcelable {

	public RouterDescriptor(String text) {
		Log.i("TOR_SERVICE", "Router Descriptor: " + text);
		StringTokenizer tok = new StringTokenizer(text, "\n");
		
		while(tok.hasMoreTokens()) {
			String token = tok.nextToken();
			
			if(token.startsWith("router ")) {
				name = token.split(" ")[1];
				ip = token.split(" ")[2];
			}
			else if(token.startsWith("uptime ")) {
				uptime = new Long(token.split(" ")[1]).longValue();
			}
			else if(token.startsWith("bandwidth ")) {
				String[] elements = token.split(" ");
				avgBw = Long.parseLong(elements[1]);
				burstBw = Long.parseLong(elements[2]);
				observedBw = Long.parseLong(elements[3]);
			}
		}
	}
	
	public GeoPoint getGeoPoint() {
		if(location == null || location.trim().length() == 0) {
			return null;
		}
		String[] tokens = location.split(",");

		if(tokens.length >= 6) {
			double lat = Double.parseDouble(tokens[4]);
			double lon = Double.parseDouble(tokens[5]);
			return new GeoPoint(((int) (lat * 1E6)), ((int) (lon * 1E6)));
		}
		else {
			return null;
		}
		
	}
	
	public String toString() {
		return ip + " " + uptime + " " + avgBw + " " + burstBw + " " + observedBw;
	}
	
	public String name;
	public String ip;
	public String location;
	public long uptime;
	public long avgBw;
	public long burstBw;
	public long observedBw;
	
	private RouterDescriptor(Parcel p) {
		name = p.readString();
		ip = p.readString();
		location = p.readString();
		uptime = p.readLong();
		avgBw = p.readLong();
		burstBw = p.readLong();
		observedBw = p.readLong();
	}

	public static final Parcelable.Creator<RouterDescriptor> CREATOR = new Parcelable.Creator<RouterDescriptor>() {
		public RouterDescriptor createFromParcel(Parcel in) {
			return new RouterDescriptor(in);
		}

		public RouterDescriptor[] newArray(int size) {
			return new RouterDescriptor[size];
		}
    };


	public int describeContents() {
		return 0;
	}
	
	public void writeToParcel(Parcel arg0, int arg1) {
		arg0.writeString(name);
		arg0.writeString(ip);
		arg0.writeString(location);
		arg0.writeLong(uptime);
		arg0.writeLong(avgBw);
		arg0.writeLong(burstBw);
		arg0.writeLong(observedBw);
	}
}
